#!/usr/bin/python

from optparse import OptionParser
import os, string, subprocess, sys,os.path

overfeat_dir = os.path.dirname(os.path.abspath(__file__))

parser = OptionParser()
parser.description = "See README.md for more details"
parser.add_option("-p", "--ppm", dest="ppm", action ="store_true", default =False, help="Input images are a stream of ppm images, instead of a list of filenames")
parser.add_option("-n", "--n_top_classes", dest="ntop", action="store", default=5, help="Number of output classes (unused when the outputs are features)")
parser.add_option("-f", "--features", dest="features", action="store_true", default=False, help="Outputs features instead of classes")
parser.add_option("-L", "--features-layer", dest="features_layer", action="store", default = None, help="Prints the output of a specitic layer. Overrides -f. The features returned with option -f alone correspond to layer 16")
(options, args) = parser.parse_args()

if len(args) < 1:
   print "Missing input image path (or -p option)"
   parser.print_help()
   sys.exit(0)

ntop = int(options.ntop)
if (options.features_layer != None) or (options.features == True):
   ntop = -1
ldpath = "LD_LIBRARY_PATH=%s/torch7-distro/installed/lib/:$LD_LIBRARY_PATH"%(overfeat_dir)
featurelayer = 16
if options.features_layer != None:
   featurelayer = int(options.features_layer)

if options.ppm == True:
   subprocess.call("%s; %s/overfeat_cl %d %d"%(ldpath, overfeat_dir, ntop, featurelayer), stdin = sys.stdin, stdout = sys.stdout)
else:
   os.system("%s; convert %s -resize 231x231^ ppm:- | %s/overfeat_cl %d %d"%(ldpath, string.join(args, " "), overfeat_dir, ntop, featurelayer))

